/**
 * 版权 (c) 2013 意定达科技有限公司
 * 保留所有权利。
 */
package cn.lunatic.init;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.jdom.Element;

import cn.lunatic.xml.JdomXMLUtil;

/**
 * @Description:
 * @author ganfeng
 * @date 2014-3-7 下午12:25:05
 */
public class Config implements Serializable{

	private static final long serialVersionUID = 5091638736083614542L;

	private final static Logger logger = Logger.getLogger(Config.class);// 获取

	private static final String LUNATIC_CONFIG_INIT_PATH = "/lunatic/initPath/entry";
	public static final String XPATHATTR_END = "']"; //xpth属性结束符号
	public static final String XPATHATTR_END_WITH_TEXT = "']/text()"; //xpth属性结束符号

	private static String initConfigFile;
	private static JdomXMLUtil jdomConfig;
	
	private static DBSource dbSource;

	private Config() {
	}

	/**
	 * @Description:初始化Config类
	 * @author ganfeng
	 * @date 2014-3-10 上午11:04:36
	 * @param initFile 初始化配置文件路径(主配置xml文件)
	 */
	public static void refresh(String initFile) {
		initConfigFile = initFile;
		refresh();
	}

	/**
	 * 
	 * @Description:刷新Config类
	 * @author ganfeng
	 * @date 2014-3-10 上午11:14:17
	 */
	public static void refresh() {
		logger.info("初始化参数配置");
		loadFromXml(initConfigFile);
		logger.info("初始化参数配置完成");
		
		logger.info("初始化项目数据源");
		dbSource = new DBSource(xpathGetNode(DBSource.LUNATIC_DAO_DATA_SOURCE_EXP));
		logger.info("初始化项目数据源完成");
	}

	/**
	 * 
	 * @Description:按配置文件规则,从主配置xml文件取配置数据
	 * @author ganfeng
	 * @date 2014-3-10 上午11:16:28
	 * @param xmlFile 主配置xml文件路径
	 */
	private static void loadFromXml(String xmlFile) {
		System.out.println(xmlFile);
		try {
			JdomXMLUtil jdom = new JdomXMLUtil();
			Element element = jdom.parseFile(xmlFile);
			if (element == null) {
				logger.info("初始化系统配置错误" + ",解析" + xmlFile + "出错!");
				throw new RuntimeException("初始化系统配置错误");
			}
			List<Element> list = JdomXMLUtil.xpathGetNodes(element,LUNATIC_CONFIG_INIT_PATH);// 循环增加配置目录
			for (Element path : list) {
				String dir = JdomXMLUtil.xpathVal(path, "text()");
				jdom.addDir(dir);
			}
			jdomConfig = jdom;
		} catch (Exception e) {
			logger.info("初始化系统配置错误", e);
			throw new RuntimeException("初始化系统配置错误", e);
		}
	}

	/**
	 * @Description:通过XPATH筛选获取XML内容
	 * @author ganfeng
	 * @date 2014-3-7 下午05:21:56
	 * @param xpathEXP
	 * @return
	 */
	public static String xpathGetVal(String xpathEXP){
		return jdomConfig.xpathVal(xpathEXP);
	}
	
	/**
	 * @Description:通过XPATH筛选获取XML节点
	 * @author ganfeng
	 * @date 2014-3-7 下午05:21:56
	 * @param xpathEXP
	 * @return
	 */
	public static Element xpathGetNode(String xpathEXP){
		return jdomConfig.xpathGetNode(xpathEXP);
	}
	
	public static Element getRoot() {
		return jdomConfig.getRoot();
	}

	/**
	 * 
	 * @Description:获取数据源
	 * @author ganfeng
	 * @date 2014-3-10 下午02:11:33
	 * @return
	 */
	public static DBSource getDbSource(){
		return dbSource;
	}
}
